﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Citi.GocAttributes.Domain
{
    public partial class Rule
    {
        public IEnumerable<RuleResult> LastRuleResults
        {
            get
            {
                return RuleResults.GroupBy(c => c.TypeRuleResult.Type)
                           .Select(g => g.OrderByDescending(c => c.TypeRuleResultId).First())
                           .Select(x => x).OrderBy(x => x.TypeRuleResult.Type);
            }
        }

        public IEnumerable<Rule> GetActiveRules()
        {
            return SelectAll<Rule>().Where(x => x.Active);
        }

        public IEnumerable<Rule> GetActiveValidRulesButException()
        {
            return SelectAll<Rule>().Where(x => x.Active && !x.Exception && x.RuleConditions.Any() && x.RuleResults.Any());
        }

        public IEnumerable<Rule> GetActiveRulesButException()
        {
            return SelectAll<Rule>().Where(x => x.Active && !x.Exception);
        }

        public void SetAsException(int id)
        {
            var ruleResult = SelectById<Rule>(id);
            ruleResult.Exception = true;
            ruleResult.Save(ruleResult);
        }

        public IEnumerable<RuleResult> GetRulesByRuleId(int ruleId)
        {
            return SelectAll<RuleResult>().Where(x => x.RuleId == ruleId).ToList();
        }
    }
}
